<?php

class NotificationShell extends AppShell {
	
	public function __construct($stdout = null, $stderr = null, $stdin = null){
		$this->uses = array(PAYMENT_CAMELCASENAME.'.PaymentNotification', PAYMENT_CAMELCASENAME.'.PaymentPagamento');
		parent::__construct($stdout, $stderr, $stdin);
	}
	
	public function main(){
		$notifications = $this->PaymentNotification->findAllByNew(true);
		foreach ($notifications as $item){
			$gateway = $item['PaymentNotification']['gateway_id'];
			App::uses('ComponentCollection', 'Controller');
			$componentName = $item['Gateway']['model'].'Component';
			App::uses($componentName, PAYMENT_CAMELCASENAME.'.Controller/Component');
			$Collection = new ComponentCollection();
			$component = new $componentName($Collection);
			$result = $component->getNotification($item['PaymentNotification']['notification_code'], $item['PaymentNotification']['gateway_id']);
			$id = $this->PaymentPagamento->getIdByCode($result->code);
			if(!$id){
				$payment_data = $this->PaymentPagamento->findByModelPagamentoAndPagamentoSystemId('Pagamento', $result->reference);
				$id = $payment_data['PaymentPagamento']['id'];
			}
// 			if($id){
				$save = array(
					'id'=>$id,
					'transaction_code'=>$result->code,
					'status_id'=>$this->PaymentPagamento->Status->getIdFromGatewayAndCode($gateway, $result->status),
					'primary_payment_method_id'=>$this->PaymentPagamento->PrimaryPaymentMethod->idFromGatewayAndCode($gateway, $result->paymentMethod->type),
					'secondary_payment_method_id'=>$this->PaymentPagamento->SecondaryPaymentMethod->idFromGatewayAndCode($gateway, $result->paymentMethod->code),
					'value'=>$result->grossAmount
				);
				if($this->PaymentPagamento->atualizarTransaction($save)){
					$save = $item;
					$save['PaymentNotification']['new'] = 0;
					$this->PaymentNotification->save($save);
				}
// 			}
		}
	}
	
}
